package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务层实现
 *
 * @author 七安
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * @param loginDto 包含用户名，密码，用户类型
     * @return 登陆结果+token
     */
    @Override
    public ResponseResult login(LoginDto loginDto) throws BusinessException {
        //获取用户名，密码，用户类型
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String utype = loginDto.getUtype();
        //判空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(utype)) {
            //如果有一个为空，返回登陆错误
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, username);
        wrapper.eq(User::getUtype, utype);
        User user = userMapper.selectOne(wrapper);
        //判空,说明用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //判断密码
        //将传来的密码进行加密
        String md5Password = DigestUtil.md5Hex(password);
        //与数据库中的比对
        if (!StringUtils.equals(md5Password, user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //生成token
        //放入一些基本信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("companyId", user.getCompanyId());
        map.put("companyName", user.getCompanyName());
        String token = JwtUtils.createToken(map, 240);
        //封装返回数据
        LoginVo loginVo = new LoginVo();
        loginVo.setUsername(user.getName());
        loginVo.setAccess_token(token);
        return ResponseResult.okResult(loginVo);
    }
}
